<template>
  <div id="contianer">
    <div class="contianer_aside_left">
      <h2>视频组菜单</h2>
      <el-tree
        ref="tree"
        :data="tableData"
        :expand-on-click-node="false"
        :props="defaultProps"
        default-expand-all
        highlight-current
        node-key="id"
        @node-click="handleNodeClick"
      />
    </div>
    <div class="contianer_aside_right">
      <div class="header_button">
        <img class="icon" @click="changeLike"
             :src="collectLikeForm.like==1?require('@/assets/images/heart_fill.png'):require('@/assets/images/heart.png')"/>
        <span>{{ collectLikeForm.likeNumber || '' }}</span>
        <img class="icon" @click="changeCollect"
             :src="collectLikeForm.collect == 1?require('@/assets/images/collect_yes.png'):require('@/assets/images/collect_no.png')"/>
        <span>{{ collectLikeForm.collectNumber || '' }}</span>
      </div>
      <div class="aside">
        <div class="video">
          <div class="header_title">{{ activeItem.chapterName }}</div>
          <div id="videoPlayer"></div>
        </div>
        <div class="list_ul">
          <div class="list_ul_li">
            <b>课程名称：</b><span>{{ addForm.folderName }}</span>
          </div>
          <div class="list_ul_li">
            <b>作者姓名：</b><span>{{ addForm.author }}</span>
          </div>
          <div class="list_ul_li">
            <b>课程简介：</b><span>{{ addForm.introduction }}</span>
          </div>
          <!-- <div class="list_ul_li">
            <b>培训课件：</b>
            <template v-if="courseware[0]">
              <el-link
                v-if="activePPTRul"
                :underline="false"
                @click="handlePreview"
                type="primary"
              >{{ courseware[0].fileName }}
              </el-link>
              <el-link
                v-else
                :underline="false"
                type="primary"
                @click="handleMessage"
              >{{ courseware[0].fileName }}
              </el-link>
            </template>
            <span v-else>无</span>
          </div> -->
        </div>
      </div>
    </div>
    <!-- <div class="recommend">
        <el-row :gutter="20">
            <el-col :span="4">
                <div style="text-align: center; line-height: 250px">
                    精品课程推荐
                </div></el-col
            >
            <el-col :span="20"
                ><el-carousel
                    :loop="false"
                    :autoplay="false"
                    height="250px"
                    width="500px"
                >
                    <el-carousel-item
                        class="el-car"
                        v-for="(list, index) in dataList"
                        :key="index"
                    >
                        <div
                            v-for="(imgList, index2) in list"
                            :key="index2"
                            class="top_img"
                        >
                            <img :src="imgList.img" :alt="imgList.title" />
                            <div class="top_img_title">
                                {{ imgList.title }}
                            </div>
                        </div>
                    </el-carousel-item>
                </el-carousel></el-col
            ></el-row
        >
    </div> -->

    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="previewVisible"
      center
      class="fullscreen_preview"
      :title="courseware && courseware.length > 0 ? courseware[0].fileName : '课件预览'"
      fullscreen>
      <el-row 
        :gutter="20"
        style="margin-top: 20px; width: 100%; height: 100% !important"
        v-loading="loading">
        <iframe
          id="iframe"
          ref="iframe"
          frameborder="0"
          height="100%"
          src=""
          width="100%"
        ></iframe>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      previewVisible: false,
      addForm: {
        author: '',
        collect: 0,
        fileType: '',
        folderName: '',
        id: null,
        introduction: '',
        likeNumber: 0,
        collectNumber: 0,
        profession: ''
      },
      isGiveLike: false,

      dataList: [
        {
          img: 'https://img2.baidu.com/it/u=1415816293,2911087723&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=338',
          title:
            '鬼鬼鬼鬼鬼鬼鬼鬼鬼鬼鬼鬼反对顶顶顶顶顶呱呱呱呱呱呱呱呱呱呱呱呱呱呱呱古古怪怪顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶'
        },
        {
          img: 'https://img.mp.itc.cn/upload/20170612/72d37f9f668549839d8cdb5d787f7ec3_th.jpg',
          title: '12322'
        },
        {
          img: 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0509%2F0a525bbaj00rblcqi003lc000p000iwm.jpg&thumbnail=660x2147483647&quality=80&type=jpg',
          title: '12322'
        },
        {
          img: 'https://img2.baidu.com/it/u=4213943477,3171054669&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=588',
          title: '12322'
        },
        {
          img: 'https://img1.baidu.com/it/u=413643897,2296924942&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500',
          title: '12322'
        },
        {
          img: 'https://img1.baidu.com/it/u=413643897,2296924942&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500',
          title: '12322'
        }
      ],
      tableData: [],
      defaultProps: {
        children: 'children',
        label: 'chapterName'
      },
      baseUrl: this.$config.VUE_APP_BASE_API,
      player: null,
      activeItem: {},
      activePPTRul: '',
      activePPTMessage: '',
      courseware: [], // 课件
      //pdf、视频预览
      collectLikeForm: {
        like: 0,
        collect: 0,
        likeNumber: 0,
        collectNumber: 0,
        selected: false
      },
      loading: false,
    }
  },
  watch: {
    activeItem(newVal, oldVal) {
      this.player && this.player.destroy()
    }
  },
  components: {},
  mounted() {
    this.getVideoDetail()
  },
  methods: {
    handlePreview() {
      this.previewVisible = true
      this.loading = true
      this.$nextTick(() => {
        let iframe = document.querySelector('#iframe')
        this.populateIframe(
          iframe,
          [['token', +localStorage.getItem('token')]],
          this.activePPTRul
        )
      })
    },

    populateIframe(iframe, headers, url) {
      var xhr = new XMLHttpRequest()
      xhr.open('GET', url)
      xhr.responseType = 'blob'
      headers.forEach((header) => {
        xhr.setRequestHeader(header[0], header[1])
      })
      // xhr.setRequestHeader("X-Amz-Server-Side-Encryption-Customer-Key-MD5", "m7AXuOLSaEQc1369IHCZGw==")
      // xhr.setRequestHeader("X-Amz-Server-Side-Encryption-Customer-Algorithm", "AES256")
      // xhr.setRequestHeader("X-Amz-Server-Side-Encryption-Customer-Key", "5svVq6aMjTLMBTD0yaIT9u735QnpHteabx6nFZUXvac=")
      xhr.onreadystatechange = () => {
        if (xhr.readyState === xhr.DONE) {
          if (xhr.status === 200) {
            console.log(URL.createObjectURL(xhr.response), 'ffff')
            this.previewUrl = URL.createObjectURL(xhr.response)
            console.log('预览地址', URL.createObjectURL(xhr.response))
            this.loading = false
            iframe.src =
              './static/pdfjs/web/viewer.html?file=' +
              URL.createObjectURL(xhr.response)
          }
        }
      }
      xhr.send()
    },
    //pdf、视频预览
    changeLike() {
      let url = this.collectLikeForm.like==1 ? '/knowledgeCollect/delete' : '/knowledgeCollect/add'
      this.$http({
        url: url,
        method: 'post',
        data: {
          collectType: 1,
          knowledgeFileId: this.$route.query.id
        }
      }).then(({data}) => {
        if (data.code == 200) {
          this.$message.success(this.collectLikeForm.like==1?'取消点赞成功':'点赞成功')
          this.collectLikeForm.like ==  1 ? this.collectLikeForm.likeNumber-- : this.collectLikeForm.likeNumber++
          this.collectLikeForm.like == 1 ? this.collectLikeForm.like = 0 : this.collectLikeForm.like = 1
        }
      })
    },
    changeCollect() {
      let url = this.collectLikeForm.collect==1 ? '/knowledgeCollect/delete' : '/knowledgeCollect/add'
      this.$http({
        url: url,
        method: 'post',
        data: {
          collectType: 2,
          knowledgeFileId: this.$route.query.id
        }
      }).then(({data}) => {
        console.log(data, 'llll')
        if (data.code == 200) {
          this.$message.success(this.collectLikeForm.collect==1?'取消收藏成功':'收藏成功')
          this.collectLikeForm.collect ==  1 ? this.collectLikeForm.collectNumber-- : this.collectLikeForm.collectNumber++
          this.collectLikeForm.collect == 1 ? this.collectLikeForm.collect = 0 : this.collectLikeForm.collect = 1
        }
      })
    },
    processTableData(data) {
      data.forEach((item) => {
        if (item.videoList && item.videoList.length > 0) {
          // 将 videoList 放入 children 中
          item.children = item.videoList.map((video) => ({
            ...video,
            chapterName: video.fileName // 设置 chapterName 为 fileName
          }));
        }

        // 如果 children 存在，递归处理
        if (item.children && item.children.length > 0) {
          this.processTableData(item.children);
        }
      });
    },
    getVideoDetail() {
      this.$http({
        url: '/knowledgeTrain/detail',
        method: 'get',
        params: {
          id: this.$route.query.id
        }
      }).then(({data}) => {
        if (data.code == 200) {
          this.addForm = data.data.course
          //点赞收藏
          this.collectLikeForm.like = data.data.course.like
          this.collectLikeForm.collect = data.data.course.collect
          this.collectLikeForm.likeNumber = data.data.course.likeNumber
          this.collectLikeForm.collectNumber = data.data.course.collectNumber

          this.tableData = data.data.video && [data.data.video]
          this.processTableData(this.tableData);
          this.activeItem.chapterName = this.addForm.defaultVideoChapter
          if (this.addForm.defaultVideoUrl) {
            setTimeout(() => {
              this.player = new this.$Player({
                id: 'videoPlayer', // 元素id
                lang: 'zh', // 设置中文
                volume: 0, // 默认静音
                autoplay: false, // 自动播放
                screenShot: false, // 开启截图功能
                // 视频地址
                url: this.addForm.defaultVideoUrl,
                // 封面图
                // poster:'',
                fluid: true, // 填满屏幕 （流式布局）
                playbackRate: [0.5, 0.75, 1, 1.5, 2] // 传入倍速可选数组
              })
            }, 300)
          }
        }
      })
    },
    async handleNodeClick(data) {
      this.activeItem = data
      console.log('章节点击',data)
      if (data.videoList) {
        const video = data.videoList.filter((item) => item.videoType === 1)
        this.courseware = data.videoList.filter((item) => item.videoType === 0)
        console.log('this.courseware', this.courseware)
        if (video.length > 0) {
          this.getVideoUrl(video[0].id)
        } else {
          this.$message.warning('该章节下无视频')
        }
        if (this.courseware.length > 0) {
          this.getPPtUrl(this.courseware[0].id)
        }
      } else {
        console.log('子节点')
        if (data.videoType === 1) {
          this.getVideoUrl(data.id)
        } else {
          await this.getPPtUrl(data.id)
          this.handlePreview()
        }
      }
    },
    getVideoUrl(id) {
      this.$http({
        url: '/knowledgeData/preview',
        method: 'get',
        params: {
          id
        }
      }).then(({data}) => {
        if (data && data.code === 200) {
          setTimeout(() => {
            this.player = new this.$Player({
              id: 'videoPlayer', // 元素id
              lang: 'zh', // 设置中文
              volume: 0, // 默认静音
              autoplay: false, // 自动播放
              screenShot: false, // 开启截图功能
              // 视频地址
              url: this.$config.VUE_APP_BASE_API_QA + data.data.downloadUrl,
              // 封面图
              // poster:'',
              fluid: true, // 填满屏幕 （流式布局）
              playbackRate: [0.5, 0.75, 1, 1.5, 2] // 传入倍速可选数组
            })
          }, 300)
        } else {
          this.$message.warning(data.msg)
        }
      })
    },
    getPPtUrl(id) {
      let that = this
      this.$http({
        url: '/knowledgeData/preview',
        method: 'get',
        params: {
          id
        }
      }).then(({data}) => {
        console.log(data)
        if (data && data.code === 200) {
          if (data.data.readAuthority) {
            that.activePPTRul = that.$config.VUE_APP_BASE_API_QA + data.data.downloadUrl
          } else {
            that.activePPTMessage = data.data.message
          }
        } else {
          that.$message.warning(data.msg)
        }
      })
    },
    // 点赞
    handleGiveLike() {
      this.$http({
        url: '/knowledgeCollect/add',
        method: 'post',
        data: {
          collectType: 1,
          knowledgeFileId: this.$route.query.id
        }
      }).then(({data}) => {
        if (data.code == 200) {
          this.isGiveLike = true
          this.getVideoDetail()
        }
      })
    },
    // 取消点赞
    handleCancelGiveLike() {
      this.$confirm('确定要取消点赞吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: '/knowledgeCollect/delete',
          method: 'post',
          data: {
            collectType: 1,
            knowledgeFileId: this.$route.query.id
          }
        }).then(({data}) => {
          if (data.code == 200) {
            this.isGiveLike = false
            this.addForm.likeNumber--
          }
        })
      })
    },
    // 收藏
    handleGiveCollect(item) {
      this.$http({
        url: '/knowledgeCollect/add',
        method: 'post',
        data: {
          collectType: 2,
          knowledgeFileId: this.$route.query.id
        }
      }).then(({data}) => {
        console.log(data, 'llll')
        if (data.code == 200) {
          this.$message.success('收藏成功')
          item.collect = 1
          this.addForm.collectNumber++
        }
      })
    },
    handleMessage() {
      this.$message.warning(this.activePPTMessage)
    },
    // 取消收藏
    handleCancelGiveCollect(item) {
      this.$confirm('确定要取消收藏吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: '/knowledgeCollect/delete',
          method: 'post',
          data: {
            collectType: 2,
            knowledgeFileId: this.$route.query.id
          }
        }).then(({data}) => {
          if (data.code == 200) {
            this.$message.success('取消收藏成功')
            item.collect = 0
            this.addForm.collectNumber--
          }
        })
      })
    }
  }
}
</script>
<style lang='scss' scoped>
::v-deep .fullscreen_preview .el-dialog__header{
  padding: 15px;
}
#contianer ::v-deep {
  .el-tree-node__content {
    height: 60px;
    line-height: 60px;
  }

  .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    background-color: #F4F6F9;
    color: #0084FF;
  }
}

#contianer {
  width: 100%;
  height: 100%;
  padding: 20px;
  display: grid;
  grid-template-columns: 320px 1fr;
  grid-column-gap: 24px;

  .contianer_aside_left {
    background: #fcfcfd;
    box-sizing: border-box;
    padding: 0 16px 16px;
    /* 中性色/gray-5 描边&禁用icon */
    border-right: 1px solid #DCDEE1;
    backdrop-filter: blur(10px);
    overflow-y: auto;

    h2 {
      font-family: 思源黑体;
      font-size: 18px;
      font-weight: 500;
      height: 60px;
      line-height: 60px;
      color: #1C2126;
      margin: 0;
    }
  }

  .contianer_aside_right {
    background-color: #FFFFFF;
    height: 100%;
    overflow-y: auto;

    .header_button {
      width: 100%;
      height: 64px;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding: 0 24px;
      border-bottom: 1px solid #D8D8D8;
      font-family: Source Han Sans;
      font-size: 18px;
      font-weight: normal;

      img {
        width: 20px;
        max-height: 20px;
        margin: 0 8px 0 16px;
        cursor: pointer;
      }
    }

    .aside {
      display: grid;
      grid-template-columns: 1fr 430px;
      padding-left: 24px;
      height: calc(100% - 64px);

      .video {
        border-right: 1px solid #D8D8D8;
        padding-right: 24px;
      }

      .header_title {
        font-family: 思源黑体;
        font-size: 16px;
        font-weight: normal;
        height: 56px;
        line-height: 56px;
        color: #1C2126;
      }

      #videoPlayer {
        flex: auto;
        height: 451px !important;
        background: #F4F5F9 url("../../../../assets/images/no_video.svg") no-repeat center;
      }

      .list_ul {
        padding: 24px;
        height: 100%;
        overflow: auto;

        .list_ul_li {
          text-align: justify;
          word-break: break-all;
          text-align-last: left;
          font-family: 思源黑体;
          font-size: 14px;
          line-height: 48px;
          min-height: 48px;

          b {
            padding-right: 16px;
            font-weight: normal;
            color: #4C5A67;
          }

          span {
            color: #1C2126;
          }
        }
      }
    }
  }

  .recommend {
    margin-top: 20px;

    &::v-deep {
      .el-car {
        width: 100%;
        display: flex;

        .top_img {
          width: 25%;
          margin-right: 10px;
          cursor: pointer;

          img {
            width: 100%;
            height: 185px;
          }

          .top_img_title {
            width: 90%;
            height: 40px;
            line-height: 40px;
            margin: 0 auto;
            text-align: center;
            font-size: 18px;
            font-weight: bold;
            color: #222222;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
        }
      }
    }
  }
}
</style>
